package org.porridge.servlet;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import jodd.mail.Email;
import jodd.mail.SendMailSession;
import jodd.mail.SmtpSslServer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.porridge.Server;
import org.porridge.entity.Book;
import org.porridge.util.Constant;
import org.porridge.util.FileUtil;
import org.porridge.util.HttpClientUtil;
import org.porridge.util.SysUtil;

/**
 * 爬取小说功能
 * @author porridge
 *
 */
public class BookServlet {
	Log log = LogFactory.getLog(this.getClass());
	
	public void seize(){
		
		String url = SysUtil.getInstance().getProperty("crawler.url");
		log.info(url);
		String result = HttpClientUtil.getData(url, Constant.CHARSET);
		
		boolean isNew = false;
		String newUrl = FileUtil.readText("lastUrl.txt");
		String lastUrl = null;
		Book book = null;
		List<Book> books = new ArrayList<Book>();
		
		Document document = Jsoup.parse(result);
		Elements list = document.getElementsByClass("booklist");
		if(list == null || list.get(0) == null)
			return;
		
		Elements domas = list.get(0).getElementsByTag("a");
		
		if(newUrl == null || "".equals(newUrl.trim())){
			isNew = true;
		}
		for(Element a:domas){
			if(isNew){
				lastUrl = a.attr("href").trim();
				book = new Book();
				book.setTitle(a.text().trim());
				book.setLink(a.attr("href").trim());
				book.setContent(getBookContent(lastUrl));
				books.add(book);
			}
			if(!isNew){
				if(a.attr("href").trim().equals(newUrl)){
					isNew = true;
				}
			}
		}
		if(lastUrl != null){
			FileUtil.writeText("lastUrl.txt", lastUrl);
		}
		if(books.size() > 0){
			sendMail(books);
		}
	}
	
	/**
	 * 爬取未读章节内容。并且保存起来
	 * @return
	 */
	private String getBookContent(String url){
		log.info("我正在抓取URL：" + url);
		String result = HttpClientUtil.getData(url, Constant.CHARSET);
		Document document = Jsoup.parse(result);
		return document.getElementById("BookText").text();
	}
	/**
	 * 将未读章节组合起来一起发送邮件出去。。
	 * @param books
	 */
	private void sendMail(List<Book> books){
		StringBuffer content = new StringBuffer();
		for(Book book:books){
			content.append("<lable>" + book.getTitle() + "</lable><hr/>");
			content.append("<div style='font-size:14px;line-height:30px;margin:5px;'>" + book.getContent() + "</div><br/><br/>");
		}
		
		String host = SysUtil.getInstance().getProperty("mail.host");
		Integer port =Integer.valueOf(SysUtil.getInstance().getProperty("mail.port"));
		String user = SysUtil.getInstance().getProperty("mail.user");
		String pas = SysUtil.getInstance().getProperty("mail.pas");
		String receiveMail = SysUtil.getInstance().getProperty("mail.receive");
		String cc = SysUtil.getInstance().getProperty("mail.cc");
		
		log.info("发送邮件内容 ... start");
		SendMailSession session = new SmtpSslServer(host, port, user, pas).createSession(); 
	    session.open();
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	    Email email = Email.create()
		        .from(user)
		        .to(receiveMail)
		        .cc(cc)
		        .subject(sdf.format(new Date())+"更新")
		        .addHtml(content.toString(),"UTF-8");
	    session.sendMail(email);
	    session.close();
	}
}
